﻿using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace HDLogCenter.Infrastructure.Utils
{
    public class DingTalkRobotHelper
    {
        private readonly string _accessToken;
        private readonly string _secret;
        private readonly HttpClient _httpClient;

        public DingTalkRobotHelper(string accessToken, string secret)
        {
            _accessToken = accessToken;
            _secret = secret;
            _httpClient = new HttpClient();
        }

        /// <summary>
        /// 发送文本消息
        /// </summary>
        public async Task<string> SendTextAsync(string content, string[] atUserIds = null, bool isAtAll = false)
        {
            long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            string sign = GenerateSign(timestamp, _secret);

            string url = $"https://oapi.dingtalk.com/robot/send?access_token=" + _accessToken + "&timestamp=" + timestamp + "&sign=" + sign;

            var payload = new
            {
                msgtype = "text",
                text = new { content },
                at = new
                {
                    atUserIds = atUserIds ?? Array.Empty<string>(),
                    isAtAll
                }
            };

            string json = JsonConvert.SerializeObject(payload, new JsonSerializerSettings
            {
                StringEscapeHandling = StringEscapeHandling.Default
            });
            var contentData = new StringContent(json, Encoding.UTF8, "application/json");

            HttpResponseMessage response = await _httpClient.PostAsync(url, contentData);
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// 生成 HmacSHA256 签名
        /// </summary>
        private static string GenerateSign(long timestamp, string secret)
        {
            string stringToSign = $"{timestamp}\n{secret}";
            using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
            {
                byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
                string base64 = Convert.ToBase64String(hash);
                return Uri.EscapeDataString(base64);
            }
        }
    }
}
